package qc.module.platform.mapper;

import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.common.core.pair.KeyValuePairDto;
import qc.module.platform.dto.dict.DictItemDto;
import qc.module.platform.entity.QcDictItem;

import java.util.List;

/**
 * DictItemMapper
 *
 * @author QuCheng Tech
 * @since 2024/3/9
 */
@Mapper
public interface DictItemMapper {
    DictItemMapper MAPPER = Mappers.getMapper(DictItemMapper.class);

    @Mapping(target = "key", source = "k")
    @Mapping(target = "value", source = "v")
    @Mapping(target = "attribute", ignore = true)
    KeyValuePairDto entityToKVPair(QcDictItem en);

    List<KeyValuePairDto> entitysToKVPairList(List<QcDictItem> list);

    @Mapping(target = "id",source = "itemid")
    @Mapping(target = "categorycode",source = "dictcode")
    @Mapping(target = "flag",source = "flag.index")
    DictItemDto toDto(QcDictItem en);

    @Mapping(target = "itemid",source = "id")
    @Mapping(target = "dictcode",source = "categorycode")
    @Mapping(target = "flag", ignore = true)
    QcDictItem toEntity(DictItemDto dto);

    List<DictItemDto> toDtoList(List<QcDictItem> list);

    /**
     * DTO转换为Entity
     *
     * @param dto 
     * @return Entity
     * @author QuCheng Tech
     * @since 2024/4/18
     */
    default QcDictItem DictItemDtoToEntity(DictItemDto dto) {
        //DTO转换为Entity
        QcDictItem en = DictItemMapper.MAPPER.toEntity(dto);

        //处理标记，非空时进行转换，空值时使用默认
        Integer flag = null;
        if (!StringUtils.isBlank(dto.getFlag())) {
            try {
                flag = Integer.parseInt(dto.getFlag());
            } catch (NumberFormatException exception) {
                //转换错误不处理，使用默认状态
            }
        }
        en.setFlag(getResourceStatusFlagEnum(flag));

        return en;
    }

    static ResourceStatusFlagEnum getResourceStatusFlagEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (ResourceStatusFlagEnum item : ResourceStatusFlagEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return ResourceStatusFlagEnum.NORMAL;
    }
}
